package com.googlecode.yami;

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class DbTree extends JComponent implements TreeSelectionListener {

    private DefaultMutableTreeNode rootDb;
    private DefaultMutableTreeNode childDb;
    private DefaultMutableTreeNode dbTableName;
    private int tablePlace = -1;

    DbTree(final Connection conn, final DbTable table) {

	setLayout(new BorderLayout());
	rootDb = new DefaultMutableTreeNode("Databases");

	ResultSet dbNames;
	ResultSet tableNames;

	// retrieving database names together with table names
	dbNames = Connect.execSQL(conn, "SHOW DATABASES");
	if (dbNames != null) {
	    try {

		// building root tree from database names
		while (dbNames.next()) {
		    String dbToSelect = dbNames.getString("Database");
		    childDb = new DefaultMutableTreeNode(dbToSelect);
		    rootDb.add(childDb);
		    tableNames = Connect.execSQL(conn,
			    "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = \""
				    + dbToSelect + "\"");

		    // adding table name for their database names
		    while (tableNames.next()) {
			String tmp = tableNames.getString("TABLE_NAME");
			dbTableName = new DefaultMutableTreeNode(tmp);
			childDb.add(dbTableName);
		    }
		}
		dbNames.close();
	    } catch (SQLException sqlDBEx) {
		sqlDBEx.printStackTrace();
	    }
	}

	JTree tree = new JTree(rootDb);
	add(tree, BorderLayout.PAGE_START);

	// Add our selection listener, it'll expand for us the databases and
	// tables
	tree.addTreeSelectionListener(new TreeSelectionListener() {
	    public void valueChanged(TreeSelectionEvent tse) {
		TreePath tp = tse.getNewLeadSelectionPath();
		if (tse.getNewLeadSelectionPath() != null) {
		    String tableName = null;
		    String dbName = null;
		    if (tp.getPathCount() == 3) {
			tableName = tp.getLastPathComponent().toString();
			dbName = tp.getPathComponent(1).toString();

			// retrieving column name from the database
			String[] clName = table.fillTableCols(conn, tableName);

			// drawing the table
			table.fillTableRows(conn, tableName, dbName, clName);

			tablePlace = MainWindow.JTP.indexOfComponent(table
				.getParent().getParent());
			// set name for current tab
			if (tablePlace != -1) {
			    MainWindow.JTP.setTitleAt(tablePlace, dbName + ":"
				    + tableName);
			    MainWindow.JTP.setToolTipTextAt(tablePlace, dbName
				    + ":" + tableName);
			}
		    }
		}
	    }
	});
    }

    public void valueChanged(TreeSelectionEvent event) {
    }
}
